﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class BallMotor : MonoBehaviour
{
    private List<BallCommand> commandQueue;
    public Rigidbody rigid;
    private float speed = 5.0f;
    private void Awake()
    {
        rigid = GetComponent<Rigidbody>();
        commandQueue = new List<BallCommand>();
    }

    public void Move(Vector3 moveDir)
    {
        Vector3 velocity = moveDir * speed;                                  //通过输入计算出速度
        transform.position = transform.position + velocity * Time.fixedDeltaTime;    //立即计算出结果
    }

    public void LocalMove(uint frame, Vector3 moveDir)
    {
        Vector3 velocity = moveDir * speed;                                  //通过输入计算出速度
        transform.position = transform.position + velocity * Time.fixedDeltaTime;    //立即计算出结果
        commandQueue.Add(new BallCommand(frame, moveDir));
    }

    public void RollBack(uint lastVerifiedClientFrame, Vector3 verifiedPosition, Vector3 verified_velocity)
    {
        //设置成权威位置
        transform.position = verifiedPosition;
        //去掉已经验证过的指令
        RemoveAllCommandsBeforeFrame(lastVerifiedClientFrame);
        rigid.velocity = verified_velocity;
        foreach (var command in commandQueue)
        {
            var moveDir = command.moveDir;
            Move(moveDir);
        }
    }

    public void RemoveAllCommandsBeforeFrame(uint frame)
    {
        for(int index = 0; index < commandQueue.Count; index++)
        {
            if(commandQueue[index].frame >= frame)
            {
                commandQueue.RemoveRange(0, index);
                break;
            }
        }
    }
}
